package com.example.onlyoffice;

import com.alibaba.fastjson.JSON;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;

/**
 * @author alexzshl
 * @since 2022/2/16 20:44
 */
@RestController
@RequestMapping("public/onlyoffice")
@CrossOrigin("*")
public class TestController {

    @PostMapping("upload")
    public R save(MultipartFile file, String status) {
        if (status == "1") {
            return R.OK();
        }

        if (file.isEmpty()) {
            return R.ERROR();
        }

        String os = System.getProperty("os.name");
        System.out.println(os);
        File saveFile = null;
        if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
            saveFile = new File("C:\\test.docx");
        } else {  //linux 和mac
            saveFile = new File("/root/test.docx");
        }

        String fileName = file.getOriginalFilename();
        String filePath = "/Users/itinypocket/workspace/temp/";

        System.out.println(file.getName());
        System.out.println(file.getContentType());
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.OK();
    }
    
    /**
     * TEST onlyoffice 编辑文件回调地址
     * 注意：必须返回 error:0 json 响应 服务端才会认为 callback 成功
     * callback 需要分析 onlyoffice 传过来的 status
     * status = 1 表示 onlyffice 进行了快速保存
     * status = 2 用户关闭浏览器页面， of 进行了保存后的返回信息
     * status = 6 用户进行了强制保存，在页面使用 ctrl+s 主动进行了保存
     * @param body
     * @return
     */
    @RequestMapping("callback1")
    public OnlyOfficeResponse callback1(@RequestBody(required = false) Map<String, Object> body) {
        System.out.println("callback api");
        String json = JSON.toJSONString(body, true);
        System.out.println(json);
    
        //for (Map.Entry<String, Object> entry : body.entrySet()) {
        //    System.out.println(entry.getKey() + ":");
        //    System.out.println(entry.getValue());
        //    System.out.println();
        //}
        return OnlyOfficeResponse.OK();
    }
    
    /**
     * TEST
     * @param body
     * @return
     */
    @RequestMapping("callback2")
    public R callback2(@RequestBody(required = false) Map<String, Object> body) {
        System.out.println("callback api");
        String json = JSON.toJSONString(body, true);
        System.out.println(json);
        
        //for (Map.Entry<String, Object> entry : body.entrySet()) {
        //    System.out.println(entry.getKey() + ":");
        //    System.out.println(entry.getValue());
        //    System.out.println();
        //}
        return R.OK();
    }
    
    /**
     * 来自官网的 callback 示例
     * @param request
     * @param response
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        PrintWriter writer = response.getWriter();

        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";

        JSONObject jsonObj = (JSONObject) new JSONParser().parse(body);

        if((long) jsonObj.get("status") == 2)
        {
            String downloadUri = (String) jsonObj.get("url");

            URL url = new URL(downloadUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();

            String pathForSave = "C:\\save.docx";
            File savedFile = new File(pathForSave);
            try (FileOutputStream out = new FileOutputStream(savedFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
            }

            connection.disconnect();
        }
        writer.write("{\"error\":0}");
    }
}
